package com.netease.jdbc;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * Configuration -> xml替代方案，体现出springboot整合
 * EnableConfigurationProperties ->启用配置文件
 *
 * @author: chenhs
 * @date: Created in 21:56 2019/11/7
 **/
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {

/*
    @Autowired
    Environment environment;*/

    /**
     * spring根据方法创建对象，参数可以注入
     *
     * @param jdbcProperties
     * @return
     */
    @Bean
    public DataSource dataSource(JdbcProperties jdbcProperties){
        System.out.println("自动装载了 数据库连接池！");
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(jdbcProperties.getUrl());
        dataSource.setUsername(jdbcProperties.getUsername());
        dataSource.setPassword(jdbcProperties.getPassword());
        dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
        return dataSource;
    }


    /**
     * spring根据方法创建对象，等价于xml定义 bean
     * @return
     */
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }




}
